<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'

import { purchasePlanDetailApi } from '@/pages/purchase/components/PurchasePlanDetail'
import type {   PurchasePlanDetail,PurchasePlanDetailListResponse } from "@/pages/purchase/components/PurchasePlanDetail" 

import { monitorApi } from '@/pages/purchase/components/PurchaseMonitor'
import type {  TenderInfoModel, TenderInfo,Tender } from "@/pages/purchase/components/PurchaseMonitor" 


import { useTokenStore } from '@/stores/token'
const tokenStore = useTokenStore();  
const currentPlanId = ref<number | null>(null)
const currentPlanName = ref<string | null>(null)
const ListFields = [
    {
      label: '详情ID',
      prop: 'purchasePlanDetailId',
      type: 'input',
      width: "80px",
    },
    {
      label: '设备名称',
      prop: 'deviceName',
      type: 'input',
      minWidth: "120px",
    },
    {
      label: '设备型号',
      prop: 'deviceModel',
      type: 'input',
      minWidth: "120px",
    },
    {
      label: '数量',
      prop: 'quantity',
      type: 'input',
      width: "80px",
    },
    {
      label: '供应商名称',
      prop: 'supplierName',
      type: 'input',
      minWidth: "120px",
    },
];
let purchasePlanDetailList = ref<PurchasePlanDetail[]>([]);
const titleName = "采购流程监控";
const searchMessage = ref({
  deviceName:'',
  deviceModel:'',
  supplierName: '',
})
const pageNum = ref(1)
const pageSize = ref(10)
const total = ref(0)

const title = ref('')
const visibleDrawer = ref(false)
const currentStageId = ref(4);

const tenderInfoModel = ref<TenderInfoModel>({
  profileId: null,
  tenderInfoId: null,
  purchasePlanId: null,
  announcement: null,
  deadline: null,
  bidSupplierName: null,
  bidPrice: null,
  contractUrl: null,
  status: null,
});
const tenderModel =ref<Tender[]>()
const tenderInfo =ref<TenderInfo>({
  tenderInfoId: null,
  purchasePlanId: null,
  announcement: null,
  deadline: null,
  bidSupplierName: null,
  bidPrice: null,
  contractUrl: null,
  status: null,
})

onMounted(async () => {
  const storedId = sessionStorage.getItem('currentPurchasePlanId')
  const storedName = sessionStorage.getItem('currentPurchasePlanName')
  console.log(sessionStorage.getItem('currentPurchasePlanStatus'))
  currentStageId.value = parseInt(sessionStorage.getItem('currentPurchasePlanStatus')!) 
  if (storedId) {
    currentPlanId.value = parseInt(storedId)
  }
  if (storedName) {
    currentPlanName.value = storedName
  }

  if(currentStageId.value == 4){
    getBiddingInfo();
  }

  await getDataListWithCondition()
})


const getDataListWithCondition = async () => {
    if (currentPlanId.value === null) {
      purchasePlanDetailList.value = []
      total.value = 0
      return
    }

    let params: {
      planId: number,
      page: number,
      size: number,
      deviceName?: string | null,
      deviceModel?: string | null,
      supplierName?: string | null
    } = {
        planId: currentPlanId.value,
        page: pageNum.value,
        size: pageSize.value,
        deviceName: searchMessage.value.deviceName || null,
        deviceModel: searchMessage.value.deviceModel || null,
        supplierName: searchMessage.value.supplierName || null,
    }


    const axiosResponse = await purchasePlanDetailApi.listPurchasePlanDetails(params);
    const responseData: PurchasePlanDetailListResponse = axiosResponse.data;
        
    purchasePlanDetailList.value = responseData.records;
    total.value = responseData.total;      
    console.log("获取到的采购计划详情:", responseData);
}
const onSizeChange = (size: number) => {
    pageSize.value = size
    getDataListWithCondition()
    ElMessage('获取成功')
}
const onCurrentChange = (num: number) => {
    pageNum.value = num
    getDataListWithCondition()
    ElMessage('获取成功')
}
const bufferName = "查看采购设备列表"
const showDrawer = () => {
  visibleDrawer.value = true;
}


const purchaseStages = [
  { id: 1, name: '待审批', description: '等待采购申请审批' },
  { id: 2, name: '审批通过', description: '审批已通过，等待进入招标环节' },
  { id: 3, name: '待招标', description: '招标准备中，等待发布招标公告' },
  { id: 4, name: '招标中', description: '招标公告已发布，等待投标' },
  { id: 5, name: '定标完成', description: '已完成定标，等待签订合同' },
  { id: 6, name: '合同签订', description: '已完成定标，等待签订合同' },
  { id: 7, name: '设备运输中', description: '设备正在运输中，请耐心等待' },
  { id: 8, name: '设备到货', description: '设备已到货，等待验收确认' },
  { id: 9, name: '已完成', description: '采购流程已全部完成' },
];


const changeStatus = async(status:number)=>{
  const statusResponse = await monitorApi.updatePurchasePlanStatus(currentPlanId.value!,status)
  console.log((statusResponse as any).message);
}


const hasSave =ref(false)
const saveBiddingDetails = async ()=>{

  if(tenderInfoModel.value.announcement==null||tenderInfoModel.value.deadline==null)
  {
    ElMessage.error("公告信息和截止时间不能为空");
  }else{
      hasSave.value = true;
      tenderInfoModel.value.purchasePlanId = currentPlanId.value;
      const tenderInfoModelResponse = await monitorApi.saveOrUpdateTender(tenderInfoModel.value)
      ElMessage.success((tenderInfoModelResponse as any).message);
  }
}

const startBid = async ()=>{
  if(tenderInfoModel.value.announcement==null||tenderInfoModel.value.deadline==null||hasSave.value==false)
  {
    ElMessage.error("未保存公告信息不能招标");
  }else{
    ElMessageBox.confirm(
            '您确定要开始招标吗',
            '注意',
            {
                confirmButtonText: '操作',
                cancelButtonText: '取消',
                type: 'warning',
            }
        )
        .then(async () => {
          await changeStatus(4);
          currentStageId.value = 4;
          getBiddingInfo();
        })
        .catch(() => {
            ElMessage({
                type: 'info',
                message: '操作取消',
            })
        })
  }
}
const getBiddingInfo=async()=>{
  const tenderInfoModelResponse = await monitorApi.getTenderInfo(currentPlanId.value!)
  tenderInfo.value = tenderInfoModelResponse.data;
  const tenderModelResponse = await monitorApi.listAllBids()
  tenderModel.value = tenderModelResponse.data;
}

const finalizeBidding = async(tender:Tender)=>{
    ElMessageBox.confirm(
        '您确定要开始定标吗',
        '注意',
        {
            confirmButtonText: '操作',
            cancelButtonText: '取消',
            type: 'warning',
        }
    )
    .then(async () => {
      tenderInfo.value.bidSupplierName = tender.tenderName;
      tenderInfo.value.bidPrice = tender.tenderPrice;
      await monitorApi.confirmBid(currentPlanId.value!,tender.tenderName!,tender.tenderPrice!)
      currentStageId.value = 6;
    })
    .catch(() => {
        ElMessage({
            type: 'info',
            message: '操作取消',
        })
    })
}

const contractUrl = ref("")

const beforeUploadHandler = ()=>{
  ElMessage('正在加载图片');
}
const uploadSuccess = async (result:any)=>{
  contractUrl.value = result.message;
  ElMessage('添加图片成功');
}

const saveUploadFiles = ()=>{
  if(contractUrl.value){
    monitorApi.saveContract(currentPlanId.value!,contractUrl.value);
    changeStatus(7);
    currentStageId.value = 7;
  }else{
    ElMessage('请先上传合同文件');
  }
}
const kownDeviceIn = ()=>{
  changeStatus(8);
  currentStageId.value = 8;
}
const arrivalFormModel = ref({
  arrivalTime:null
});
const saveDeviceInfo = ()=>{
  if(arrivalFormModel.value.arrivalTime){
    monitorApi.deviceArrival(currentPlanId.value!,arrivalFormModel.value.arrivalTime);
    changeStatus(9);
    currentStageId.value = 9;
  }else{
    ElMessage('请先填写设备到货日期');
  }
}

const changeState =  async(planId:number,status:number) => {
  await monitorApi.updatePurchasePlanStatus(planId, status)
  currentStageId.value = 1;
}

const changeStateBox = (planId:number,status:number) => {
    ElMessageBox.confirm(
        `你确定要申请采购吗`,
        '注意：请在决定之前认真查看采购设备列表',
        {
            confirmButtonText: '操作',
            cancelButtonText: '取消',
            type: 'warning',
        }
    )
    .then(() => {
        changeState(planId,status)
    })
    .catch(() => {
        ElMessage({
            type: 'info',
            message: '操作取消',
        })
    })
}



</script>






<template>
  <el-card class="page-container">
    <template v-if="currentPlanId== null">
        <div class="header">
            <span>请从采购计划中选择某一计划查看详情</span>
        </div>
    </template>
    <template #header v-if="currentPlanId !== null" >
        <div class="header">
            <span>{{ titleName }}-------{{ currentPlanName }}</span>
            <div class="extra">
                <el-button v-if="currentStageId!=8" type="primary" @click="showDrawer()">{{ bufferName }}</el-button>
            </div>
        </div>
    </template>
    
    <template v-if="currentPlanId !== null">
    <template v-if="currentPlanId !== null">
      <div class="purchase-process-flow">
        <div
          v-for="stage in purchaseStages"
          :key="stage.id"
          :class="{
            'process-node': true,
            'process-node-done': stage.id < currentStageId,       // 已完成的阶段
            'process-node-current': stage.id === currentStageId, // 当前活跃的阶段  
            'process-node-future': stage.id > currentStageId,    // 尚未开始的阶段
            // 'process-node-rejected': stage.id === rejectedStageId // 新增：被驳回的阶段            
          }"
        >
          <div class="node-circle"></div>
          <div class="node-name">{{ stage.name }}</div>
        </div>
      </div>

      <div class="stage-content-area">
        <div v-if="currentStageId === 0">
          <p>
            <el-icon color="red" style="vertical-align: middle; margin-bottom: 5px;font-size: 40px;"><Warning /></el-icon>
            申请被驳回
          </p>
          <p>请检查你的采购计划列表 并联系财务人员</p>
          <div class="flex-style">
            <el-button type="primary" @click="changeStateBox(currentPlanId,1)">重新提交采购申请</el-button>            
          </div>
        </div>
        <div v-if="currentStageId === 1">
          <p>当前进度：{{ purchaseStages[currentStageId-1].description }}</p>
          <div class="flex-style">
            <el-button type="info" @click="ElMessage.warning('已通知相关人员准备采购申请')">提醒处理</el-button>            
          </div>
        </div>

        <div v-if="currentStageId === 3">
          <p>当前进度：{{ purchaseStages[currentStageId-1].description }}</p>
          <el-form :model="tenderInfoModel" label-width="100px" style="max-width: 1400px;">
            <el-form-item label="招标公告">
              <el-input
                v-model="tenderInfoModel.announcement"
                type="textarea"
                :rows="10"
                placeholder="请填写详细的招标公告内容"
              ></el-input>
            </el-form-item>
            <el-form-item label="截止时间">
              <el-date-picker
                v-model="tenderInfoModel.deadline"
                placeholder="选择截止日期"
                type="datetime"
                value-format="YYYY-MM-DD HH:mm:ss"
                style="width: 100%;"
              ></el-date-picker>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="saveBiddingDetails();">保存招标信息</el-button>
              <el-button type="primary" @click="startBid();">开始招标</el-button>
            </el-form-item>
          </el-form>
        </div>


        <div v-if="currentStageId === 4">
          <p>当前进度：{{ purchaseStages[currentStageId-1].description }}</p>
          <el-form :model="tenderInfo" label-width="100px" style="max-width: 1400px;">
            <el-form-item label="招标公告">
              <el-input
                v-model="tenderInfo.announcement"
                type="textarea"
                :rows="10"
                disabled
              ></el-input>
            </el-form-item>
            <el-form-item label="截止时间">
              <el-date-picker
                v-model="tenderInfo.deadline"
                type="date"
                disabled
                value-format="YYYY-MM-DD"
                style="width: 100%;"
              ></el-date-picker>
            </el-form-item>
          </el-form>

          <el-divider content-position="left">投标人及报价</el-divider>
          <div>
            <el-row v-for="(tender, index) in tenderModel" :key="index" style="margin-bottom: 10px;">
              <el-col :span="2">
                <span>投标人: <strong>{{ tender.tenderName }}</strong></span>
              </el-col>
              <el-col :span="2">
                <span>报价: <strong>¥ {{ tender.tenderPrice }}</strong></span>
              </el-col>
              <el-col :span="4">
                <el-button type="success" @click="finalizeBidding(tender)" style="width: 200px;">定标</el-button>
              </el-col>
            </el-row>
          </div>
        </div>

        <div v-if="currentStageId === 6">
          <p>当前进度：{{ purchaseStages[currentStageId - 1].description }}</p>
          <h4>- 上传合同文件：</h4>
                    <!-- 
                        auto-upload自动上传
                        action:接口路径
                        name:设置的文件字段名
                        header：token
                        on-success成功回调函数
                    -->
                    <el-upload class="avatar-uploader" 
                    :auto-upload="true" 
                    :show-file-list="false" 
                    action="/api/procedure/monitor/contract/uploadFile"
                    name="file" 
                    :headers="{ 'Authorization': tokenStore.token }" 
                    :on-success="uploadSuccess"
                    :before-upload="beforeUploadHandler"
                    >
                      <!-- 使用 el-popover 实现悬浮大图预览 -->
                      <el-popover
                        v-if="contractUrl"
                        placement="right"
                        trigger="hover"
                        width="666"
                      >
                        <template #reference>
                          <img :src="contractUrl" class="avatar" />
                        </template>
                        <img :src="contractUrl" style="width: 100%" />
                      </el-popover>

                      <template v-else>
                        <div class="upload-preview-wrapper">
                          <el-icon class="avatar-uploader-icon"><Plus /></el-icon>
                        </div>
                      </template>
                    </el-upload>
          <el-button type="primary" @click="saveUploadFiles()" style="margin: 20px 0 0 0;">保存合同</el-button>
        </div>

        <div v-if="currentStageId === 7">
          <p>当前进度：{{ purchaseStages[currentStageId-1].description }}</p>
          <el-button type="primary" @click="kownDeviceIn()">设备已经到货,填写到货信息</el-button>
        </div>

        <div v-if="currentStageId === 8">
          <p>当前进度：{{ purchaseStages[currentStageId - 1].description }}</p>
          <h4>- 填写设备到货信息：</h4>
          <el-form :model="arrivalFormModel" label-width="120px" style="max-width: 600px;">
            <el-form-item label="设备到货时间">
              <el-date-picker
                v-model="arrivalFormModel.arrivalTime"
                type="datetime"
                value-format="YYYY-MM-DD HH:mm:ss"
                style="width: 100%;"
              ></el-date-picker>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="saveDeviceInfo()">提交到货信息</el-button>
            </el-form-item>
          </el-form>

          <el-table  :data="purchasePlanDetailList" style="width: 100%">
            <el-table-column
              v-for="col in ListFields"
              :key="col.prop"
              :label="col.label"
              :prop="col.prop"
              :width="col.width"
              :min-width="col.minWidth"
            >
            </el-table-column>
            <template #empty>
              <el-empty description="没有数据" />
            </template>
          </el-table>
          <el-pagination v-model:current-page="pageNum" v-model:page-size="pageSize" :page-sizes="[3, 5, 7, 10]"
              layout="jumper, total, sizes, prev, pager, next" background :total="total" @size-change="onSizeChange"
              @current-change="onCurrentChange" style="margin-top: 20px; justify-content: flex-end" />
        </div>

        <div v-if="currentStageId === 9">
          <p>当前进度：{{ purchaseStages[currentStageId-1].description }}</p>
        </div>
      </div>
    </template>

    <el-drawer v-model="visibleDrawer" :title="title" direction="rtl" size="50%">
        <el-card class="page-container">
          <el-table :data="purchasePlanDetailList" style="width: 100%">
            <el-table-column
              v-for="col in ListFields"
              :key="col.prop"
              :label="col.label"
              :prop="col.prop"
              :width="col.width"
              :min-width="col.minWidth"
            >
            </el-table-column>
            <template #empty>
              <el-empty description="没有数据" />
            </template>
          </el-table>
          <el-pagination v-model:current-page="pageNum" v-model:page-size="pageSize" :page-sizes="[3, 5, 7, 10]"
              layout="jumper, total, sizes, prev, pager, next" background :total="total" @size-change="onSizeChange"
              @current-change="onCurrentChange" style="margin-top: 20px; justify-content: flex-end" />
        </el-card>

    </el-drawer>

    </template>
  </el-card>
</template>



<style lang="scss" scoped>
.page-container {
    min-height: 100%;
    box-sizing: border-box;
    // padding: 20px;
    .header {
        display: flex;
        align-items: center;
        justify-content: space-between;
        // margin-bottom: 20px;
    }
}

.purchase-process-flow {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 30px;
    position: relative;
    padding: 0 20px;
}

.process-node {
    display: flex;
    flex-direction: column;
    align-items: center;
    position: relative;
    flex-grow: 1;
    text-align: center;

    &:not(:last-child)::after {
        content: '';
        position: absolute;
        top: 15px;
        left: 50%;
        width: 100%;
        height: 2px;
        background-color: #e0e0e0;
        transform: translateX(1px);
        z-index: 0;
    }
}

.node-circle {
    width: 30px;
    height: 30px;
    border-radius: 50%;
    background-color: #e0e0e0;
    display: flex;
    justify-content: center;
    align-items: center;
    color: #fff;
    font-weight: bold;
    z-index: 1;
    transition: background-color 0.3s ease, border-color 0.3s ease;
    border: 2px solid #e0e0e0;
}

.node-name {
    margin-top: 8px;
    font-size: 14px;
    color: #909399;
    transition: color 0.3s ease;
}

.process-node-done {
    .node-circle {
        background-color: #67c23a;
        border-color: #67c23a;
    }
    .node-name {
        color: #67c23a;
    }
    &::after {
        background-color: #67c23a;
    }
}

.process-node-current {
    .node-circle {
        background-color: #409eff;
        border-color: #409eff;
    }
    .node-name {
        color: #409eff;
        font-weight: bold;
    }
}

.process-node-future {
    .node-circle {
        background-color: #e0e0e0;
        border-color: #e0e0e0;
    }
    .node-name {
        color: #909399;
    }
}

.stage-content-area {
    margin-top: 30px;
    padding: 20px;
    border: 1px dashed #dcdfe6;
    border-radius: 4px;
    min-height: 150px;
    background-color: #f7f7f7;
}


:deep(.avatar-uploader .el-upload) {

  background-color: #e0f2f7;
  width: 300px; 
  height: 424px; 
  // overflow: hidden;
}

/* 如果你还想调整图标本身的颜色或大小 */
:deep(.avatar-uploader .avatar-uploader-icon) {
  color: #8c939d;
  font-size: 28px;
}

:deep(.avatar-uploader .el-upload:hover) {
  border-color: #409eff;
  background-color: #d9ecff;
}

:deep(.avatar-uploader .el-upload img) {
    width: 100%;
    height: 100%;
    display: block;
    object-fit: cover;
}


.el-divider {
    margin: 40px 0 60px 0;
    background-color: black;
}

.avatar-uploader {
    :deep() {
        .avatar {
            width: 178px;
            height: 178px;
            display: block;
        }

        .el-upload {
            border: 1px dashed var(--el-border-color);
            border-radius: 6px;
            cursor: pointer;
            position: relative;
            overflow: hidden;
            transition: var(--el-transition-duration-fast);
        }

        .el-upload:hover {
            border-color: var(--el-color-primary);
        }

        .el-icon.avatar-uploader-icon {
            font-size: 28px;
            color: #8c939d;
            width: 178px;
            height: 178px;
            text-align: center;
        }
    }
}

.editor {
    width: 100%;

    :deep(.ql-editor) {
        min-height: 200px;
    }
}
.my-select {
  width: 250px;
}

:deep(.el-input.is-disabled .el-textarea__inner){
  -webkit-text-fill-color: #000000 !important;
  color: #000000 !important;
  font-weight: bold;
}

.upload-preview-wrapper {
  position: relative;

  &:hover .image-hover-preview {
    opacity: 1;
    visibility: visible;
  }
}

.image-hover-preview {
  position: absolute;
  top: 0;
  left: 100%;
  margin-left: 10px;
  z-index: 999;
  width: 300px;
  max-height: 400px;
  border: 1px solid #dcdfe6;
  background-color: #fff;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.3);
  padding: 6px;
  border-radius: 4px;
  opacity: 0;
  visibility: hidden;
  transition: opacity 0.3s ease;

  img {
    width: 100%;
    height: auto;
    display: block;
  }
}
</style>